define([
    "../../service.js",
    "pager",
    "../../assets/vendor/bootstrap/bootstrap-dropdown",
    "../../assets/vendor/jquery-ui-1.11.4.min",
    "../../assets/vendor/datatimepicker-language"
], function(api) {
    function MobileClient() {
        //以下是判断是否在移动客户端
        var sUserAgent = navigator.userAgent.toLowerCase();
        var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
        var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
        var bIsAndroid = sUserAgent.match(/android/i) == "android";
        if (bIsIpad || bIsIphoneOs || bIsAndroid) {
            return true;
        }
        return false;
    }
    function getCookie(name)
    {  
        var nameEQ = name + "=";  
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) 
        {  
            var c = ca[i];  
            while(c.charAt(0)==' ')
            {
                c = c.substring(1,c.length);
            }
            if(c.indexOf(nameEQ) == 0) 
            {
                return unescape(c.substring(nameEQ.length,c.length));
            }
        }
        return false;  
    }

    function clearCookie(name)

    {  
        setCookie(name, "", -1);
    }

    function setCookie(name, value, seconds){  
        seconds = seconds || 0;  
        var expires = "";
        if(seconds != 0 ){
            var date = new Date();
            date.setTime(date.getTime()+(seconds*1000));  
            expires = ";expires="+date.toGMTString();
        }  
        document.cookie = name+"="+escape(value)+expires+";path=/";
    }
    var vm = avalon.define({
        $id: 'myVideos',
        recordVideoList: [],
        $setting: {},
        param: {
            method: api.getRecordVideoList,
            query: {
                PageSize: 12,
                PageIndex: 1
            }
        },
        zgbh: '',
        searchkey: '',
        startTime: '',
        endTime: '',
        logon: '',
        uri: '',
        nickname:'',
        showTable: false,
        defaultAlert:'无记录',
        logout:function(){
            vm.zgbh = ''
            vm.uri = ''
            vm.logon = ''
            vm.nickname = ''
            clearCookie('avanickname')
            clearCookie('avazgbm')
            clearCookie('avauri')
            vm.getRecordVideoList()
            vm.showTable = false
        },
        getRecordVideoList: function(query, cb) {
            if(vm.$setting.enableQQAuth){
                if (vm.logon != '') {
                    vm.param.query.ParentEmployee = vm.uri;
                }else{
                    vm.showTable = false;
                    return;
                }
            }else{
                vm.param.query.ParentEmployee = vm.zgbh;
            }
            if(vm.param.query.ParentEmployee!=''){
                vm.showTable = true;
                vm.defaultAlert = '加载中';
                return api.getItems(avalon.mix(vm.param), function(res) {

                    if (res.query) {
                        vm.pager.totalItems = res.query.recordCount;
                        vm.pager.currentPage = res.query.pageIndex;
                        vm.pager.perPages = res.query.pageSize;
                        vm.pager.pageCount = res.query.pageCount;
                        var listPager = avalon.vmodels.listPager;

                        if(listPager){
                            listPager.totalItems = res.query.recordCount;
                            listPager.currentPage = res.query.pageIndex;
                            listPager.pageCount = res.query.pageCount;
                            listPager.perPages = res.query.pageSize;
                        }
                        if(cb){
                            cb(res.query)
                        }

                        // avalon.scan();
                        // console.log(vm.pager)
                    }
                    if (res.list) {
                        vm.recordVideoList = _.merge([], res.list)
                    }
                    if(vm.recordVideoList.length == 0){
                        vm.defaultAlert = '无记录'
                    }

                })
            }
            
        },
        pager: {
            currentPage: 1,
            perPages: 12,
            showJumper: false,
            alwaysShowNext: true, //@config {Boolean} 总是显示向后按钮
            alwaysShowPrev: true,
            pageCount: 1,
            totalItems:1,
            onJump: function(e, data) {
                vm.param.query.PageIndex = data.currentPage;
                vm.getRecordVideoList(vm.param, function(data) {
                    vm.pager.currentPage = data.pageIndex;
                });
            }
        },
        showDialog: function(id) {
            if(!MobileClient()){

                document.getElementById("iframe").setAttribute("src", "http://pt.ava.com.cn/qq/authorize.jsp?receive=myVideos&extra=" + location.origin + "/open/qq/receive.html");
            }else{
                location.href = "http://pt.ava.com.cn/qq/authorize.jsp?receive=myVideos&extra=" + location.origin + "/open/qq/receive.html"
            }
            avalon.vmodels[id].toggle = true;
        },
        showAvaDialog: function(id) {
            avalon.vmodels[id].toggle = true;
        },
        avalogon: function(id) {

            $.ajax({
                url: 'http://xy.ava.com.cn/lxx/j_spring_security_check',
                data: {
                    j_username: $('[name="ava_name"]').val(),
                    j_password: $('[name="ava_password"]').val(),
                    isAppLogon: 1,
                    deviceType: 5
                },
                type: 'post',
                success: function(res) {
                    if (res.status == 0) {
                        vm.uri = 'AVA:' + (res.result && res.result.userId);
                        vm.logon = 'avaLogon';
                        avalon.vmodels[id].toggle = false;
                        vm.getRecordVideoList(vm.param);
                    } else {
                        alert(res.msg);
                    }
                },
                error: function() {
                    alert("出错！")
                }
            })
        },
        stafflogon:function(){

            // if(vm.zgbm!=""){
            if($('input[name="zgbh"]').val()!=''){
                vm.logon = 'stafflogon'
                vm.nickname = "职工"+$('input[name="zgbh"]').val()
                setCookie('avazgbm',$('input[name="zgbh"]').val())
                setCookie('avanickname',vm.nickname)
            

            }else{
                alert('请输入教职工号');
            }
        },
        dialogOpts: {
            title: 'QQ-登记',
            height: 500,
            width: 900,
            container: 'myVideos'

        },
        avaDialogOpts: {
            title: 'AVA-登记',
            height: 500,
            width: 600,
            container: 'myVideos'
        },
        searchVideos: function() {}
    })
    vm.searchVideos = function() {

        vm.param.query.SearchKey = vm.searchkey;
        vm.param.query.StartTimeBegin = vm.startTime
        vm.param.query.StartTimeEnd = vm.endTime!=''?(vm.endTime+' 23:59:59'):''
        vm.getRecordVideoList(vm.param);
    }

    vm.$watch("setting", function(param) {
        vm.$setting = avalon.define(
            avalon.mix(vm.$setting, param))
        if(!vm.$setting.enableQQAuth){
            console.log(avalon.vmodels.app.currentStateModel)
            if(avalon.vmodels.app.currentStateModel.vmName=="myVideos"){
                vm.getRecordVideoList(vm.param)
            }
        }
    })



    return avalon.controller(function($ctrl) {
        // 视图渲染后，意思是avalon.scan完成
        $ctrl.$onRendered = function() {

            $(".dateui").datepicker({
                "dateFormat": "yy-mm-dd"
            })
            $('.searchOpts input').on('keyup',function(evt){
                var e = evt||window.event;
                if(e.keyCode == 13){
                    vm.searchVideos()
                }
            })
            $('.searchOpts input[name="zgbh"]').on('keyup',function(evt){
                var e = evt||window.event;
                if(e.keyCode == 13){
                    vm.stafflogon()
                }
            })
            if(getCookie('avazgbm')){
                vm.zgbh = getCookie('avazgbm')
                vm.logon = "stafflogon"
            }
            if(getCookie('avauri')){
                vm.uri = getCookie('avauri')
                vm.logon = "QQLogon"
            }
            if(getCookie('avanickname')){
                vm.nickname = getCookie('avanickname')
            }
            if(vm.logon!=''){
                vm.getRecordVideoList(vm.param);
            }

        };
        // 进入视图
        $ctrl.$onEnter = function(param, rs, rj) {
            var tt = location.hash.replace(/\#\!/g, '')
            if(tt.indexOf('?')!=-1){
                var currentHash = tt.split('?')[1].split('&');
                console.log(currentHash)
                for(var i=0;i<currentHash.length;i++){
                    var attr = currentHash[i].split('=');
                    if(attr[0]=="authQQ"){
                        vm.logon = "QQLogon"
                    }else if(attr[0]=="code"){
                        if(attr[1]){
                            //console.log(1)
                            // vm.zgbm = decodeURIComponent(attr[1])
                            vm.uri = decodeURIComponent(attr[1])
                            // setCookie('avazgbm',vm.zgbm)
                            setCookie('avauri',vm.uri)

                            //console.log(vm.zgbm)
                        }
                    }else if(attr[0]=="chapter"){
                        if(attr[1]){
                            console.log(decodeURIComponent(attr[1]))
                            vm.chapterselect.chapter = decodeURIComponent(attr[1])
                        }
                    }else if(attr[0]=="startTime"){
                        if(attr[1]){
                           vm.chapterselect.startTimeTip = decodeURIComponent(attr[1])
                            //$('#startTime').val(decodeURIComponent(attr[1]))
                        }
                    }else if(attr[0]=="endTime"){
                        if(attr[1]){
                            vm.chapterselect.endTimeTip = decodeURIComponent(attr[1])
                        }
                    }else if(attr[0]=="parentRecordEquipment"){
                        if(attr[1]){
                            vm.equipment = attr[1]
                        }
                    }else{
                        console.log(decodeURI(attr[1]))
                        if(attr[1]){
                            vm[attr[0]] = decodeURIComponent(attr[1])
                        }
                    }
                    //console.log(i)
                }
                if(vm.nickname!=''){
                    setCookie('avanickname',vm.nickname)
                }
                //console.log(vm)
                location.hash = location.hash.split("?")[0]
                // vm.data = new Date().toLocaleDateString().replace(/\//g,'-');

            }
            // 获取登录状态
            
            
            window.setValue = function(uri,nickname) {
                if (!avalon.vmodels['myVideosdialog']) return;
                vm.uri = uri;
                vm.logon = 'QQLogon';
                vm.nickname = nickname
                setCookie('avazgbm',vm.zgbm)
                setCookie('avauri',vm.uri)
                 setCookie('avanickname',vm.nickname)
                avalon.vmodels['myVideosdialog'].toggle = false
                if(vm.logon!=''){
                    vm.getRecordVideoList(vm.param);
                }
            }

        };
        // 对应的视图销毁前
        $ctrl.$onBeforeUnload = function() {
            vm.logon = '';
            vm.showTable = false;
            vm.zgbh = ''
            vm.uri = ''
            var listPager = avalon.vmodels.listPager;

            if(listPager){
                listPager.totalItems = 0;
                listPager.currentPage = 1;
                listPager.pageCount = 0;
                listPager.perPages = 12;
            }

        };
        $ctrl.$vmodels = [vm];
    })
})
